package com.duomn.mybatis.plugins.parse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SQLParser {
	
	private static Logger logger = LoggerFactory.getLogger(SQLParser.class);
	
	private String sql;
	
	/** sql中包含哪些table */
	private List<String> tabList;
	
	
	List<String> tables = new ArrayList<String>() {
		private static final long serialVersionUID = -7967581078115372196L;
		{
			add("order_1");
			add("order_2");
			add("order_3");
		}
	};
	
	public void parse(String sql) {
		
		List<String> tabEnds = Arrays.asList("where", "having", "group", "order", "limit");
		
		System.out.println(tables);
		String lowSql = sql.toLowerCase();
		// " \t\n\r\f"
		StringTokenizer tokenizer = new StringTokenizer(lowSql);
		
		
		String type = tokenizer.nextToken(); // select/insert/delete/update
		if ("select".equals(type)) {
			logger.info("SELECT");
			StringBuilder preTabSql = new StringBuilder();
			StringBuilder tableSql = new StringBuilder();
			StringBuilder whereSql = new StringBuilder();
			StringBuilder sortSql = new StringBuilder();
			StringBuilder limitSql = new StringBuilder();

			preTabSql.append(type);
			while (tokenizer.hasMoreTokens()) { // from之前的语句
				String column = tokenizer.nextToken();
				preTabSql.append(" ").append(column);
				if ("from".equals(column)) {
					break;
				}
			}	
			
			while (tokenizer.hasMoreTokens()) { // where 之前的table语句
				String tabEnd = tokenizer.nextToken();
				tableSql.append(" ").append(tabEnd);
				if (tabEnds.contains(tabEnd)) {
					break;
				}
			}
			
			boolean hasSort = false;
			boolean hasLimit = false;
			while (tokenizer.hasMoreTokens()) { // where之后的条件语句
				String tabEnd = tokenizer.nextToken();
				whereSql.append(" ").append(tabEnd);
				if (tabEnds.contains(tabEnd)) {
					if ("order".equals(tabEnd)) {
						hasSort = true;
					}
					if ("limit".equals(tabEnd)) {
						hasLimit = true;
					}
					break;
				}
			}
			
			if (hasSort) {
				while (tokenizer.hasMoreTokens()) { // order by 语句之后的条件语句
					String sortStr = tokenizer.nextToken();
					if (!"limit".equals(sortStr)) {
						sortSql.append(" ").append(sortStr);
					} else {
						hasLimit = true;
						break;
					}
				}
			}
			
			if (hasLimit) {
				limitSql.append(" limit");
				while (tokenizer.hasMoreTokens()) {
					limitSql.append(" ").append(tokenizer.nextToken());
				}
			}
			
			logger.info("preTabSql:" + preTabSql.toString());
			logger.info("tabSql:" + tableSql.toString());
			logger.info("wherSql:" + whereSql.toString());
			logger.info("sortSql:" + sortSql.toString());
			
		} else if ("insert".equals(type)) {
			logger.info("INSERT");
			String into = tokenizer.nextToken();
			if (!"into".equals(into)) {
				throw new IllegalArgumentException(sql);
			}
			String tableName = tokenizer.nextToken("(");
			logger.info("tableName:" + tableName);

			String columns = tokenizer.nextToken(")");
			String[] cols = columns.substring(1).split(",( \t\n\r\f)");
			List<String> colList = Arrays.asList(cols);
			logger.info("colList:" + colList);
			
		} else if ("delete".equals(type)) {
			logger.info("DELETE");
			String from = tokenizer.nextToken();
			if (!"from".equals(from)) {
				throw new IllegalArgumentException(sql);
			}
			String tableName = tokenizer.nextToken();
			System.out.println(tableName);
			
			while (tokenizer.hasMoreTokens()) {
				if ("where".equals(tokenizer.nextToken())) {
					break;
				}
			}
			
			if (!tokenizer.hasMoreTokens()) return;
			
			StringBuilder whereSql = new StringBuilder();
			while (tokenizer.hasMoreTokens()) {
				whereSql.append(" ").append(tokenizer.nextToken());
			}
			System.out.println(whereSql.toString());
		} else if ("update".equals(type)) {
			String tableName = tokenizer.nextToken();
			System.out.println(tableName);
			while (tokenizer.hasMoreElements()) {
				if ("where".equals(tokenizer.nextToken())) {
					break;
				}
			}
			
			if (!tokenizer.hasMoreTokens()) return;
			
			StringBuilder whereSql = new StringBuilder();
			while (tokenizer.hasMoreTokens()) {
				whereSql.append(" ").append(tokenizer.nextToken());
			}
			System.out.println(whereSql.toString());
		}
		
	}

	
	public static void main(String[] args) {
		String sql = "  select * from orders where \n created_ts > 1000 and order_no = ?";
		SQLParser parser =  new SQLParser();
		parser.parse(sql);
		
		String sql2 = " insert into orders(order_no, created_ts) values(?, ?)";
		parser.parse(sql2);
		
		
		String sql3 = "delete from orders where order_no = ? ";
		parser.parse(sql3);
		
		String sql4 = "update orders set state = ? where order_no = ?";
		parser.parse(sql4);
	}
	
}
